    //
//  SwitchViewController.m
//  PhotoFrame
//
//  Created by William on 11-5-5.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import "SwitchViewController.h"
#import "PhotoFramePortraitViewController.h"
#import "PhotoFrameLandscapeViewController.h"
#import "PhotoFrameFullScreenViewController.h"
#import "PhotoFrameVideoPlayViewController.h"
#import "PhotoFrameGroupViewController.h"
#import "CalendarUtils.h"
#import "SettingViewController.h"
#import "GlobalSettingUtils.h"

#define DEFAULT_SETTING_FRAME CGRectMake(25, 30, 20, 20)
#define GRUOP_SETTING_FRAME CGRectMake(950, 30, 20, 20)

#define DEFAULT_POPOVER_FRAME CGRectMake(frame.origin.x - 30, frame.origin.y, frame.size.width, frame.size.height)
@implementation SwitchViewController
@synthesize portraitViewController;
@synthesize landscapeViewController;
@synthesize fullScreenViewController;
@synthesize groupViewController=_groupViewController;
@synthesize calendarObject;
@synthesize togglePopoverButton;
@synthesize popoverController;
@synthesize photoPollingTimer;
@synthesize timePollingTimer;
@synthesize gblConf;
@synthesize photoPathList;
@synthesize viewImage;
@synthesize imageAsset;
@synthesize imageURL=_imageURL;
@synthesize image=_image;
@synthesize library=library_;
@synthesize playURL=_playURL;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    _image = [[UIImage alloc] init];
    
	[self initGblConf];
	//[self loadAllPhoto];
	
	CalendarUtils *utils = [[CalendarUtils alloc] init];
    CalendarObjectDTO *tmpCalendarObject = [utils getCalendarInfo];
	self.calendarObject = tmpCalendarObject;
	[tmpCalendarObject release];
	[utils release];
		
    _groupViewController = [[PhotoFrameGroupViewController alloc] initWithNibName:@"GroupView" bundle:nil];
    [self.view addSubview:self.groupViewController.view];
    
	PhotoFrameFullScreenViewController *fullScreenView = [[PhotoFrameFullScreenViewController alloc] initWithNibName:@"FullScreenView" bundle:nil];
	self.fullScreenViewController = fullScreenView;
	[self.view addSubview:fullScreenView.view];
	[fullScreenView release];
	
	PhotoFramePortraitViewController *portraitView = [[PhotoFramePortraitViewController alloc] initWithNibName:@"PortraitView" bundle:nil];
	portraitView.calendarObject = self.calendarObject;
	self.portraitViewController = portraitView;
	[self.view addSubview:portraitView.view];
	[portraitView release];
	
	PhotoFrameLandscapeViewController *landscapeView = [[PhotoFrameLandscapeViewController alloc] initWithNibName:@"LandscapeView" bundle:nil];
	landscapeView.calendarObject = self.calendarObject;
	self.landscapeViewController = landscapeView;
	[self.view addSubview:landscapeView.view];
	[landscapeView release];
    
	togglePopoverButton = [UIButton buttonWithType:UIButtonTypeCustom];
	[togglePopoverButton setImage:[UIImage imageNamed:@"set_btn.png"] forState:UIControlStateNormal];
	[togglePopoverButton setFrame:DEFAULT_SETTING_FRAME];
	[togglePopoverButton addTarget:self action:@selector(togglePopover) forControlEvents:UIControlEventTouchUpInside];
	
	[self.view addSubview:togglePopoverButton];
	
	NSString *layout = [[GlobalSettingUtils getGlobalConf] objectForKey:@"layout"];
	
	[self initViewOrder:[layout intValue]];
	
    [self loadImage];
    [self initTimer];
    
	[super viewDidLoad];
}

- (void) initGblConf {
	// load properties from user document folder
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString* sandBoxpath = [NSString stringWithFormat:@"%@/%@",documentsDirectory,@"globalconf.plist"];
	NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithContentsOfFile:sandBoxpath];
	
	// load from app default resources folder
	if (dict == nil) {
		NSString *path = [[NSBundle mainBundle] pathForResource:@"globalconf" ofType:@"plist"];
		dict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
	}
	
	self.gblConf = dict;
	[dict release];
}



- (void) initTimer {
	NSDictionary *playlist = [GlobalSettingUtils getPlayList];
	if (playlist == nil || [playlist count] == 0) {
		return;
	}
	NSString *polling = [gblConf objectForKey:@"polling"];
	NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:[polling intValue] target:self selector:@selector(refreshPhoto:) userInfo:nil repeats:YES];
	self.photoPollingTimer = timer;
//	
//	timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(log) userInfo:nil repeats:YES];
//	self.timePollingTimer = timer;
//	[timer release];
//	timer = nil;
}

- (void) refreshPhoto: (NSTimer*) newTimer {
	//if ([self.photoPathList count] == 0)  {
//		NSLog(@"%@", @"Didn't find aviliable photos under the folder.");
//		return;
//	}
//	
	NSDictionary *dict = [GlobalSettingUtils getPlayList];
	if (dict == nil || [dict count] == 0) {
		NSLog(@"%@", @"Didn't find aviliable photos or videos under the folder.");
		return;
	}
	
	[self loadImage];
}

- (void) loadMediaResource: (NSString *) type image:(UIImage*) image {
    if (([type isEqualToString:@"Photo"] == NO && [type isEqualToString:@"Video"] == NO) || image == nil) {
        return;
    }
  if ([type isEqualToString:@"Video"]) {
      PhotoFrameVideoPlayViewController *videoPlayer = [[PhotoFrameVideoPlayViewController alloc] init];
      [self.view setAutoresizesSubviews:NO];
      CGRect rect;
      switch (currentFrame) {
          case 1:
              rect = CGRectMake(0.0, 0.0, 808.0, 579.0);
              break;
          case 2:
              rect = CGRectMake(0.0, 0.0, 808.0, 768.0);
              break;
          case 4:
              rect = CGRectMake(0.0, 0.0, 640.0, 500.0);
              break;
          default:
              rect = CGRectMake(0.0, 0.0, 1024.0, 768.0);
              break;
      }
      videoPlayer.delegate = self;
      [videoPlayer.view setFrame:rect];
      
      [self.view addSubview:videoPlayer.view];
      [videoPlayer playMovie:self.playURL];
      [self.view bringSubviewToFront:togglePopoverButton];
  } else {
        
    CGSize size = image.size;
    if (size.width <= 0 || size.height <=0 ) {
        return;
    }
    CGFloat ratio = 0;
    CGFloat ratio1 = 0;
    ratio = (ratio1 = 808.0 / size.width) > (ratio = 579.0 / size.height) ? ratio : ratio1;
      if (currentFrame == 4) {
          ratio = ratio * 0.8;
      }
      CGRect rect = CGRectMake(0.0, 0.0, ratio * size.width, ratio * size.height);
      
    CGFloat fullSizeRatio = 0;
    CGFloat ratio2 = 0;
    if (size.width <= 1024.0 && size.height <= 768.0) {
        fullSizeRatio = 1.0;
    } else {
        fullSizeRatio = (ratio2 = 1024.0 / size.width) > (fullSizeRatio = 768.0 / size.height) ? fullSizeRatio : ratio2;
    }
      
    CGRect fullSizeRect = CGRectMake(0.0, 0.0, fullSizeRatio * size.width, fullSizeRatio * size.height);

      CGPoint landsscapCenter = CGPointMake(1024.0/2, currentFrame == 4 ? 332.0 + 50.0 : 332.0);
    CGPoint portraitCenter = CGPointMake(808.0/2, 768.0/2);
    CGPoint fullScreenCenter = CGPointMake(1024.0/2, 768.0/2);
    switch (currentFrame) {
        case 1:
            [self.landscapeViewController.photoImageView setFrame:rect];
            [self.landscapeViewController.photoImageView setCenter:landsscapCenter];
            [self.landscapeViewController.photoImageView setImage:image];
            [self.view bringSubviewToFront:self.landscapeViewController.photoImageView];
            break;
        case 2:
            [self.portraitViewController.photoImageView setFrame:rect];
            [self.portraitViewController.photoImageView setCenter:portraitCenter];
            [self.portraitViewController.photoImageView setImage:image];
            [self.view bringSubviewToFront:self.portraitViewController.photoImageView];
            break;
        case 3:
            [self.fullScreenViewController.photoImageView setFrame:fullSizeRect];
            [self.fullScreenViewController.photoImageView setCenter:fullScreenCenter];
            [self.fullScreenViewController.photoImageView setImage:image];
            [self.view bringSubviewToFront:self.fullScreenViewController.photoImageView];
            break;
        case 4:
            [self.groupViewController.photoImageView setFrame:rect];
            [self.groupViewController.photoImageView setCenter:landsscapCenter];
            [self.groupViewController.photoImageView setImage:image];
            [self.view bringSubviewToFront:self.groupViewController.photoImageView];
        }
    }
    [self.view bringSubviewToFront:self.landscapeViewController.photoImageView];
    [self.view bringSubviewToFront:self.togglePopoverButton];
}
- (void) loadImage {
    NSDictionary *dict = [GlobalSettingUtils getPlayList];
	if (dict == nil || [dict count] == 0) {
		return;
	}
	int random = arc4random() % [dict count];
	self.playURL = [[dict allKeys] objectAtIndex:random];
	NSString *type = [dict objectForKey:self.playURL];
    
    _imageURL = [NSURL URLWithString:self.playURL]; 
    if (!self.library) {
		library_ = [[ALAssetsLibrary alloc] init];
	}
    
    ALAssetsLibraryAssetForURLResultBlock resultsBlock = ^(ALAsset *asset) {
        self.imageAsset = asset;
        ALAssetRepresentation *representation = [asset defaultRepresentation];
        CGImageRef imageRef = [representation fullScreenImage];
        // Make sure that the UIImage we create from the CG image has the appropriate
        // orientation, based on the EXIF data from the image.
        ALAssetOrientation orientation = [representation orientation];
        self.image = [UIImage imageWithCGImage:imageRef scale:1.0 orientation:(UIImageOrientation)orientation];
    };
    ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError *error){
        NSLog(@"FAILED! due to error in domain %@ with error code %d", error.domain, error.code);
        abort();
    };
    
    [self.library assetForURL:self.imageURL resultBlock:resultsBlock failureBlock:failureBlock];
    [self loadMediaResource:type image:self.image];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight;
}

- (IBAction)togglePopover {
	if (![popoverController isPopoverVisible]) {
		SettingViewController *settingViewController = [[SettingViewController alloc] init];
		settingViewController.delegate = self;
		UIPopoverController *tmpPopoverController = [[UIPopoverController alloc] initWithContentViewController:settingViewController];
		self.popoverController = tmpPopoverController;
		[popoverController setPopoverContentSize:CGSizeMake(350, 500)];
		CGRect frame = [togglePopoverButton frame];
		CGRect popoverRect = (currentFrame == 4) ? frame : DEFAULT_POPOVER_FRAME;
		[self.popoverController presentPopoverFromRect:popoverRect inView:self.view permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
		//[self.view addSubview:settingViewController.view];
		[settingViewController release];
		[tmpPopoverController release];
	}
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
	self.portraitViewController = nil;
	self.landscapeViewController = nil;
	self.fullScreenViewController = nil;
	self.popoverController = nil;
    self.imageAsset = nil;
	
	self.gblConf = nil;
	self.photoPathList = nil;
    self.library = nil;
    self.playURL = nil;
    self.groupViewController = nil;
}

- (void)dealloc {
	[portraitViewController release];
	[landscapeViewController release];
	[fullScreenViewController release];
	[popoverController release];
	
	[gblConf release];
	[photoPathList release];
    [imageAsset release];
    [super dealloc];
}

#pragma mark -
#pragma mark Global Delegationg Source Methods
- (void) setPhotoPollingTimerInterval:(NSUInteger)interval {
	NSDictionary *dict = [GlobalSettingUtils getPlayList];
	if (dict == nil || [dict count] == 0) {
		return;
	}
	NSLog(@"New Interval ===========> %d", interval);
	NSTimer *newTimer = [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(refreshPhoto:) userInfo:nil repeats:YES];
	if (self.photoPollingTimer != newTimer) {
		if ([photoPollingTimer isValid] == YES) {
			[photoPollingTimer invalidate];
			self.photoPollingTimer = nil;
		}
		self.photoPollingTimer = newTimer;
	}	
}

- (void) closePopover {
	[popoverController dismissPopoverAnimated:YES];
}

- (void) initViewOrder:(int)order {
	switch (order) {
		case 1:
			[self.view bringSubviewToFront:self.landscapeViewController.view];
            [togglePopoverButton setFrame:DEFAULT_SETTING_FRAME];
			break;
		case 2:
			[self.view bringSubviewToFront:self.portraitViewController.view];
            [togglePopoverButton setFrame:DEFAULT_SETTING_FRAME];
			break;
		case 3:
			[self.view bringSubviewToFront:self.fullScreenViewController.view];
            [togglePopoverButton setFrame:DEFAULT_SETTING_FRAME];
			break;
        case 4:
            [self.view bringSubviewToFront:self.groupViewController.view];
            [togglePopoverButton setFrame:GRUOP_SETTING_FRAME];
            break;
	}
	
	currentFrame = order;
	
	[self.view bringSubviewToFront:self.togglePopoverButton];
}

- (void) pauseTimer {
	[self.photoPollingTimer invalidate];
	self.photoPollingTimer = nil;
}
- (void) resumeTimer {
	NSString *polling = [[GlobalSettingUtils getGlobalConf] objectForKey:@"polling"];
	[self setPhotoPollingTimerInterval:[polling intValue]];
	if ([self.photoPollingTimer isValid] == YES) {
		[self.photoPollingTimer fire];
	}
}
- (CGPoint) getCurrentCenter {
	switch (currentFrame) {
		case 1:
			return CGPointMake(1024.0/2, 332.0);
			break;
		case 2:
			return CGPointMake(808.0/2, 768.0/2);
			break;
		case 3 :
			return CGPointMake(1024.0/2, 768.0/2);
            break;
        case 4:
			return CGPointMake(1024.0/2, 390.0);
			break;
	}
}

- (CGRect) getCurrentRect {
	switch (currentFrame) {
		case 1:
			return [self.landscapeViewController.photoImageView frame];
			break;
		case 2:
			return [self.portraitViewController.photoImageView frame];
			break;
        case 4:
			return CGRectMake(0.0, 0.0, 640, 500.0);
			break;
		default:
			return CGRectMake(0.0, 0.0, 1024.0, 768.0);
			break;
	}
    
}

@end
